/**
 * Copyright &copy; 2012-2014 hongsuan.pplive All rights reserved.
 */
package com.hongsuan.pplive.modules.cms.web.front;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cnjson.common.config.Global;
import com.cnjson.db.persistence.Page;
import com.cnjson.common.web.BaseController;
import com.google.common.collect.Lists;
import com.hongsuan.pplive.modules.cms.entity.Article;
import com.hongsuan.pplive.modules.cms.entity.Category;
import com.hongsuan.pplive.modules.cms.entity.Result;
import com.hongsuan.pplive.modules.cms.entity.UserCourse;
import com.hongsuan.pplive.modules.cms.service.ArticleDataService;
import com.hongsuan.pplive.modules.cms.service.ArticleService;
import com.hongsuan.pplive.modules.cms.service.CategoryService;
import com.hongsuan.pplive.modules.cms.service.UserCourseService;

/**
 * 网站Controller
 * @author ThinkGem
 * @version 2013-5-29
 */
@Controller
@RequestMapping(value = "${frontPath}")
public class FrontController extends BaseController{
	
	@Autowired
	private ArticleService articleService;
	@Autowired
	private ArticleDataService articleDataService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private UserCourseService userCourseService;
	
	/**
	 * 网站首页
	 * @throws Exception 
	 */
	@RequestMapping
	public String index(Model model,HttpServletRequest reqeust) throws Exception {
		try{
			String artisan_id = reqeust.getParameter(ARTISAN_ID);
			String token = reqeust.getParameter(USER_PARAMS_TOKEN);
			if(((StringUtils.isBlank(artisan_id)||StringUtils.isBlank(token))) && !artisan_id.equalsIgnoreCase("1")){
				throw new Exception("验证信息错误:artisan_id or token is null");
			}

            if(!artisan_id.equalsIgnoreCase("1") && !artisan_id.equalsIgnoreCase("4")){
                boolean flag = articleService.checkHljToken(artisan_id, token);
                if(!flag){
                    throw new Exception("验证错误");
                }
            }

			model.addAttribute("isIndex", true);
			Article article = new Article(new Category());
			article.setPosid("1");
            article.setArtisan_id(artisan_id);
			List<Article> bananerList = articleService.findListFornt(article);
			model.addAttribute(ARTISAN_ID,artisan_id);
			model.addAttribute(USER_PARAMS_TOKEN,token);
			model.addAttribute("bananerList", bananerList);
		}catch(Exception e){
			logger.info(e.getMessage());
			throw e;
		}
		return "modules/cms/front/themes/"+Global.getConfig("site.theme")+"/frontIndex";
	}

    /**
     * 网站首页
     */
    @RequestMapping(value = "index${urlSuffix}")
    public String indexPage(Model model,HttpServletRequest reqeust) {
        return "redirect:"+Global.getFrontPath();
    }
    
    @ResponseBody
	@RequestMapping(value = "listArticle")
	public Result listArticle(Model model,HttpServletRequest request,Integer pageNo,
			@RequestParam(required=false, defaultValue="10") Integer pageSize,Article article) {
    	Result result = Result.createResult().setSuccess(false);
    	try{
    		Page<Article> page = new Page<Article>(pageNo, pageSize);
    		String cid = request.getParameter("cid");
    		String parentId = request.getParameter("parentId");
    		if(article == null){
    			article = new Article();
    		}
    		String artisan_id = request.getParameter(ARTISAN_ID);
    		if(StringUtils.isBlank(artisan_id)){
    			throw new Exception("手艺人信息为空");
    		}
    		
    		Category category = new Category();
    		if(StringUtils.isNotBlank(cid)){
    			category.setId(cid);
    		}
    		if(StringUtils.isBlank(parentId)){
    			article.setParentId(parentId);
    		}
    		article.setCategory(category);
    		page = articleService.findListForntPage(page, article);
    		result.setPage(page);
    		result.setSuccess(true);
    	}catch(Exception e){
    		result.setDesc(e.getMessage());
    	}
    	return result;
    }
	
	/**
	 * 内容列表
	 */
	@RequestMapping(value = "list-{categoryId}${urlSuffix}")
	public String list(@PathVariable String categoryId, @RequestParam(required=false, defaultValue="1") Integer pageNo,
			@RequestParam(required=false, defaultValue="15") Integer pageSize, Model model,HttpServletRequest request) throws Exception{
		Category category = categoryService.get(categoryId);
		if (category==null){
			return "error/404";
		}
		String artisan_id = request.getParameter(ARTISAN_ID);
		if(StringUtils.isBlank(artisan_id)){
			throw new Exception("手艺人信息为空");
		}
		String token = request.getParameter(USER_PARAMS_TOKEN);
		model.addAttribute(ARTISAN_ID,artisan_id);
		model.addAttribute(USER_PARAMS_TOKEN,token);
		// 2：简介类栏目，栏目第一条内容
		if("2".equals(category.getShowModes()) && "article".equals(category.getModule())){
			// 如果没有子栏目，并父节点为跟节点的，栏目列表为当前栏目。
			List<Category> categoryList = Lists.newArrayList();
			if (category.getParent().getId().equals("1")){
				categoryList.add(category);
			}else{
				categoryList = categoryService.findByParentId(category.getParent().getId());
			}
			model.addAttribute("category", category);
			model.addAttribute("categoryList", categoryList);
			// 获取文章内容
			Page<Article> page = new Page<Article>(1, 1, -1);
			Article article = new Article(category);
			page = articleService.findPage(page, article);
			if (page.getList().size()>0){
				article = page.getList().get(0);
				article.setArticleData(articleDataService.get(article.getId()));
				articleService.updateHitsAddOne(article.getId());
			}
			model.addAttribute("article", article);
			return "modules/cms/front/themes/"+Global.getConfig("site.theme")+"/"+getTpl(article);
		}else{
			List<Category> categoryList = categoryService.findByParentId(category.getId());
			// 展现方式为1 、无子栏目或公共模型，显示栏目内容列表
			if("1".equals(category.getShowModes())||categoryList.size()==0){
				// 有子栏目并展现方式为1，则获取第一个子栏目；无子栏目，则获取同级分类列表。
				if(categoryList.size()>0){
					category = categoryList.get(0);
				}else{
					// 如果没有子栏目，并父节点为跟节点的，栏目列表为当前栏目。
					if (category.getParent().getId().equals("1")){
						categoryList.add(category);
					}else{
						categoryList = categoryService.findByParentId(category.getParent().getId());
					}
				}
				model.addAttribute("category", category);
				model.addAttribute("categoryList", categoryList);
				// 获取内容列表
				if ("article".equals(category.getModule())){
					Page<Article> page = new Page<Article>(pageNo, pageSize);
					//System.out.println(page.getPageNo());
					page = articleService.findPage(page, new Article(category));
					model.addAttribute("page", page);
					// 如果第一个子栏目为简介类栏目，则获取该栏目第一篇文章
					if ("2".equals(category.getShowModes())){
						Article article = new Article(category);
						if (page.getList().size()>0){
							article = page.getList().get(0);
							article.setArticleData(articleDataService.get(article.getId()));
							articleService.updateHitsAddOne(article.getId());
						}
						model.addAttribute("article", article);
						return "modules/cms/front/themes/"+Global.getConfig("site.theme")+"/"+getTpl(article);
					}
				}
				String view = "/frontList";
                //System.out.println("else 栏目第一条内容 _2 :"+category.getSite().getTheme()+","+Global.getConfig("site.theme"));
				return "modules/cms/front/themes/"+Global.getConfig("site.theme")+view;
				//return "modules/cms/front/themes/"+category.getSite().getTheme()+view;
			}
			// 有子栏目：显示子栏目列表
			else{
				model.addAttribute("category", category);
				model.addAttribute("categoryList", categoryList);
				String view = "/frontListCategory";
				return "modules/cms/front/themes/"+Global.getConfig("site.theme")+view;
			}
		}
	}

	/**
	 * 内容列表（通过url自定义视图）
	 */
	@RequestMapping(value = "listc-{categoryId}-{customView}${urlSuffix}")
	public String listCustom(@PathVariable String categoryId, @PathVariable String customView, @RequestParam(required=false, defaultValue="1") Integer pageNo,
			@RequestParam(required=false, defaultValue="15") Integer pageSize, Model model) {
		Category category = categoryService.get(categoryId);
		if (category==null){
			return "error/404";
		}
		List<Category> categoryList = categoryService.findByParentId(category.getId());
		model.addAttribute("category", category);
		model.addAttribute("categoryList", categoryList);
		return "modules/cms/front/themes/"+Global.getConfig("site.theme")+"/frontListCategory"+customView;
	}

	/**
	 * 显示内容
	 */
	@RequestMapping(value = "view-{categoryId}-{contentId}${urlSuffix}")
	public String view(@PathVariable String categoryId, @PathVariable String contentId, Model model,HttpServletRequest request)throws Exception {
		Category category = categoryService.get(categoryId);
		if (category==null){
			return "error/404";
		}
		String artisan_id = request.getParameter(ARTISAN_ID);
		if(StringUtils.isBlank(artisan_id)){
			throw new Exception("手艺人信息为空");
		}
		String token = request.getParameter(USER_PARAMS_TOKEN);
		model.addAttribute(ARTISAN_ID,artisan_id);
		model.addAttribute(USER_PARAMS_TOKEN,token);
		//TODO 校验改用户是否有访问视频权限
		Page<Article> page = new Page<Article>(1, 1, -1);
		Article article= new Article(category);
		article.setId(contentId);
		article.setArtisan_id(artisan_id);
		page = articleService.findListForntPage(page, article);
		if (page.getList().size() <= 0){
			throw new Exception("该用户无权限访问该视频");
		}
		article = page.getList().get(0);
		if(article == null){
			throw new Exception("该用户无权限访问该视频");
		}
		//TODO 更新为已学或者插入
		if("0".equals(article.getUserCourse().getCourseLearned())){
			UserCourse userCourse = new UserCourse();
			userCourse.setId(artisan_id);
			userCourse.setCourseId(contentId);
			userCourse.setCourseLearned("1");
			userCourse.setRemarks("0");
			userCourseService.saveFront(userCourse);
		}
		
		if ("article".equals(category.getModule())){
			// 如果没有子栏目，并父节点为跟节点的，栏目列表为当前栏目。
			List<Category> categoryList = Lists.newArrayList();
			if (category.getParent().getId().equals("1")){
				categoryList.add(category);
			}else{
				categoryList = categoryService.findByParentId(category.getParent().getId());
			}
			// 获取文章内容
			article = articleService.get(contentId);
			if (article==null || !Article.DEL_FLAG_NORMAL.equals(article.getDelFlag())){
				return "error/404";
			}
			// 文章阅读次数+1
			articleService.updateHitsAddOne(contentId);
			// 将数据传递到视图
			model.addAttribute("category", categoryService.get(article.getCategory().getId()));
			model.addAttribute("categoryList", categoryList);
			article.setArticleData(articleDataService.get(article.getId()));
			model.addAttribute("article", article);
//			return "modules/cms/front/themes/"+category.getSite().getTheme()+"/"+getTpl(article);
            return "modules/cms/front/themes/"+Global.getConfig("site.theme")+"/"+getTpl(article);
		}
		return "error/404";
	}
	@RequestMapping(value = "myCourse${urlSuffix}")
	public String MyCourse(Model model,HttpServletRequest request) throws Exception{
		String artisan_id = request.getParameter(ARTISAN_ID);
		if(StringUtils.isBlank(artisan_id)){
			throw new Exception("手艺人信息为空");
		}
		String token = request.getParameter(USER_PARAMS_TOKEN);
		model.addAttribute(ARTISAN_ID,artisan_id);
		model.addAttribute(USER_PARAMS_TOKEN,token);
		return "modules/cms/front/themes/"+Global.getConfig("site.theme")+"/frontMyArticle";
	}
	
	/**
	 * 站点地图
	 */
	@RequestMapping(value = "map${urlSuffix}")
	public String map(Model model) {
		return "modules/cms/front/themes/"+Global.getConfig("site.theme")+"/frontMap";
	}

    private String getTpl(Article article){
        return Article.DEFAULT_TEMPLATE;
    }
	
}
